package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        //根据用户名查询数据库创建user对象
        User user = userDao.findByUsername(username);
        if (user==null){
            return null;
        }

        Integer userId = user.getId();
        //根据userid查询数据库查询角色信息
        Set<Role> roles = roleDao.findByUserId(userId);
        //判断角色是否为空
        if (roles !=null && roles.size()>0){
            //遍历角色
            for (Role role : roles) {
                Integer roleId = role.getId();
                //根据角色id查询能访问那些模块
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                //判断模块是否为空
                if (permissions != null && permissions.size() >0){
                    //为角色设置模块信息
                    role.setPermissions(permissions);
                }
                //为用户设置角色信息
                user.setRoles(roles);
            }
        }
        //返回user对象
        return user;
    }
}
